/**
 * 下载文件资源到临时文件夹
 * Created by litong on 15-7-28.
 */
var urlparse = require('url').parse
    , http = require('http')
    , fs = require('fs')
    , path = require('path')
    , async = require('async')
    , mkdirp = require('mkdirp')
    , config = require('./config');

/**
 * 资源下载器
 * @param link      链接地址
 * @constructor
 */
var RsDownloader = function(link){
    this.link = link;
    this._imageList = {};
    /**
     * 下载资源
     * @param callback  下载完成后的回调
     */
    this.downloadRs = function(callback){
        async.auto({
            //先下载event.json
            downloadJson : function(callback) {
                this._downLoadJson(callback);
            }.bind(this),
            //同时下载音频文件
            downloadAudio_ogg : function(callback){
                this._downLoadAudioRs("audio.ogg",callback);
            }.bind(this),
            downloadAudio_mp3 : function(callback){
                this._downLoadAudioRs("audio.mp3",callback);
            }.bind(this),
            downloadAudio_aac : function(callback){
                this._downLoadAudioRs("audio.aac",callback);
            }.bind(this),
            //下载完成eventjson后解析它并下载图片
            parserJson : ['downloadJson',function(callback, results) {
                fs.readFile(config.tmpPath + "/originData/event.json",{encoding:'utf-8'}, function (err,bytesRead) {
                    callback(err,bytesRead);
                });
            }],
            downloadImg : ['parserJson',function(callback, results) {
                var data=JSON.parse(results.parserJson);
                var records = data.records;
                async.each(records, function(record, cb) {
                    if(record.class == "DRFileRecord"){//如果是图片 ppt file 类资源
                        //判断重复下载
                        if(this._imageList.hasOwnProperty(record.relativeSourcePath)){
                            cb();
                        }
                        this._downLoadImgRs(record.relativeSourcePath,function(){
                            this._imageList[record.relativeSourcePath] = true;
                            cb();
                        }.bind(this));
                    }else
                        cb();
                }.bind(this), function(err) {
                    callback(err);
                }.bind(this));
            }.bind(this)]
    }, function (err) {
            callback(err);
        }.bind(this));
    }
}

/**
 * 下载图片文件
 * @param fileName  文件名
 * @param callback  下载完成的回调
 * @private
 */
RsDownloader.prototype._downLoadImgRs = function(fileName,callback){
    this._download(this.link+"/"+fileName,function(err) {
        callback(err);
    },fileName.substring(0,fileName.lastIndexOf('/')));
}

/**
 * 下载音频文件
 * @param fileName  文件名
 * @param callback  下载完成的回调
 * @private
 */
RsDownloader.prototype._downLoadAudioRs = function(fileName,callback){
    this._download(this.link+"/"+fileName,function(err) {
        callback();
    });
}

/**
 * 下载json文件
 * @param callback  下载完成的回调
 * @private
 */
RsDownloader.prototype._downLoadJson = function(callback){
    this._download(this.link+"/event.json",function(err) {
        callback(err);
    });
}

/**
 * 下载方法
 * @param url           下载地址
 * @param callback      下载成功回调
 * @param savePath      下载到的指定位置，可选
 * @private
 */
RsDownloader.prototype._download = function(url,callback,savePath){
    url = path.normalize(url).replace("http:/","http://");
    var fileName = url.substring(url.lastIndexOf('/'),url.length);
    var folder = config.tmpPath + "/originData";
    if(savePath)
        folder += "/" + savePath;
    var savefile = folder + fileName;

    //格式化本地路径
    folder = path.normalize(folder);
    savefile = path.normalize(savefile);
    async.waterfall([
        function(callback){
            mkdirp(folder, function(err) {
                callback(err);
            });
        }
    ], function (err) {
        if(err){
            callback(err);
            return ;
        }
        var urlinfo = urlparse(url);
        var options = {
            method: 'GET',
            host: urlinfo.hostname,
            path: urlinfo.pathname
        };
        if(urlinfo.port) {
            options.port = urlinfo.port;
        }
        if(urlinfo.search) {
            options.path += urlinfo.search;
        }
        var req = http.request(options, function(res) {
            var status = res.statusCode;
            if (status == 200) {
                var writestream = fs.createWriteStream(savefile);
                writestream.on('close', function() {
                    callback(null, res);
                });
                res.pipe(writestream);
            } else {
                callback(new Error("下载资源失败："+url + "statuscode:"+status));
            }

        });
        req.end();
    });
}


module.exports = RsDownloader;